package com.simon.app.service;

import android.accessibilityservice.AccessibilityService;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import androidx.core.app.NotificationCompat;

import com.simon.app.MainActivity;
import com.simon.app.R;
import com.simon.app.entity.RuleDetail;
import com.simon.app.entity.RuleEntity;
import com.simon.app.utils.LogUtil;
import com.simon.app.utils.ParseUtil;
import com.simon.app.utils.ToastUtil;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// 实现 无障碍服务
public class AdDogService extends AccessibilityService {

    private static AdDogService mInstance;
    public static boolean mStatusStartUpAdListen = false;
    public static boolean mStatusDialogAdListen = false;
    public static boolean mStatusSuperModeListen = false;

    private ExecutorService executor = Executors.newFixedThreadPool(6);
    private List<RuleEntity> ruleList;

    public static boolean isRunning() {
        return mInstance != null;
    }

    /*
     * 【必须】
     * 通过这个函数可以接收系统发送来的AccessibilityEvent，接收来的AccessibilityEvent是经过过滤的，
     * 过滤是在配置工作时设置的。
     */
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        LogUtil.i("AccessibilityEvent=>" + event.toString());
        LogUtil.i("读取设置状态 mStatusStartUpAdListen=>" + mStatusStartUpAdListen + "| mStatusDialogAdListen=>" + mStatusDialogAdListen);

        // 开屏广告 skip
        startUpScreenAdSkip(event);
        // 弹窗广告 skip
        dialogAdSkip(event);
        // 超级模式 skip
//        superModeSkip(accessibilityEvent);
    }

    // 开屏广告 skip
    private void startUpScreenAdSkip(AccessibilityEvent event) {
        if (!mStatusStartUpAdListen) {
            return;
        }

        if (event != null) {
            LogUtil.i("开屏广告-监听中......");
            AccessibilityNodeInfo currentNodeInfo = getCurrentWindowRootNode();
            if (currentNodeInfo != null) {
                // 跳过按钮
                List<AccessibilityNodeInfo> skipBtnNodes = currentNodeInfo.findAccessibilityNodeInfosByText("跳过");

                if (skipBtnNodes != null && !skipBtnNodes.isEmpty()) {
                    AccessibilityNodeInfo skipBtn = skipBtnNodes.get(0);
                    LogUtil.i("检测到广告节点：" + String.valueOf(skipBtn));
                    // 模拟点击
                    skipBtn.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                    String tips = "检测到==>跳过==>执行点击";
                    ToastUtil.showShortToast(this, tips);
                    LogUtil.i(tips);
                }

                // 关闭按钮
                List<AccessibilityNodeInfo> closeBtnNodes = currentNodeInfo.findAccessibilityNodeInfosByText("关闭");
                if (closeBtnNodes != null && !closeBtnNodes.isEmpty()) {
                    AccessibilityNodeInfo closeBtn = closeBtnNodes.get(0);
                    LogUtil.i("检测到广告节点：" + String.valueOf(closeBtn));
                    // 模拟点击
                    closeBtn.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                    String tips = "检测到==>关闭==>执行点击";
                    ToastUtil.showShortToast(this, tips);
                    LogUtil.i(tips);
                }

            }
        }

    }

    // 弹窗广告 skip
    private void dialogAdSkip(AccessibilityEvent event) {
        if (!mStatusDialogAdListen) {
            return;
        }

        if (event != null) {
            LogUtil.i("弹窗广告-监听中......");
            AccessibilityNodeInfo dialogNodeInfo = getCurrentWindowRootNode();
            if (dialogNodeInfo != null) {
                String viewId = dialogNodeInfo.getPackageName() + ":id/" + "close";
                List<AccessibilityNodeInfo> closeNodes = dialogNodeInfo.findAccessibilityNodeInfosByViewId(viewId);

                if (closeNodes != null && !closeNodes.isEmpty()) {
                    AccessibilityNodeInfo dialogCloseNode = closeNodes.get(0);
                    dialogCloseNode.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                }
            }
        }
    }

    // 超级模式 skip
    private void superModeSkip(AccessibilityEvent event) {
        if (event != null && mStatusSuperModeListen) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    if (ruleList != null) {
                        for (RuleEntity re : ruleList) {
                            for (RuleDetail rd : re.getRules()) {
                                if (searchNode(rd.getId()) != null) {
                                    AccessibilityNodeInfo node = searchNode(rd.getAction());
                                    if (node != null) {
                                        node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                                        LogUtil.i("超级模式下：" + String.valueOf(node));
                                    }
                                }
                            }
                        }
                    }
                }
            });
        }
    }

    // 匹配广告节点
    private AccessibilityNodeInfo searchNode(String filter) {
        AccessibilityNodeInfo rootNode = getCurrentWindowRootNode();
        if (rootNode != null) {

            List<AccessibilityNodeInfo> nodeInfosByText = rootNode.findAccessibilityNodeInfosByText(filter);
            if (!nodeInfosByText.isEmpty()) {
                return nodeInfosByText.get(0);
            }

            String viewId = rootNode.getPackageName() + ":id/" + filter;
            List<AccessibilityNodeInfo> nodeInfosByViewId = rootNode.findAccessibilityNodeInfosByViewId(viewId);
            if (!nodeInfosByViewId.isEmpty()) {
                return nodeInfosByViewId.get(0);
            }
        }
        return null;
    }

    // 获取当前窗口节点
    private AccessibilityNodeInfo getCurrentWindowRootNode() {
        try {
            return getRootInActiveWindow();
        } catch (Exception e) {
            if (e.getMessage() != null) {
                LogUtil.i("根节点异常:" + e.getMessage());
            }
            return null;
        }
    }

    /*
     * 【必须】
     * 这个在系统想要中断AccessibilityService返给的响应时会调用。
     * 在整个生命周期里会被调用多次。
     */
    @Override
    public void onInterrupt() {
        LogUtil.i("系统-断开了连接 onInterrupt");
    }

    /*
     * 【可选】
     * 在系统将要关闭这个AccessibilityService会被调用。在这个方法中进行一些释放资源的工作。
     */
    @Override
    public boolean onUnbind(Intent intent) {
        LogUtil.i("无障碍服务=>断开 onUnbind");
        return super.onUnbind(intent);
    }

    /*
     * 【可选】
     * 系统会在成功连接上你的服务的时候调用这个方法，在这个方法里你可以做一下初始化工作，
     * 例如设备的声音震动管理，也可以调用setServiceInfo()进行配置工作
     */
    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        LogUtil.i("无障碍服务=>连接成功 onServiceConnected");

        mInstance = this;
        executor.execute(new Runnable() {
            @Override
            public void run() {
                LogUtil.i("广告规则-加载中.......");
                ruleList = ParseUtil.loadAdRules(AdDogService.this);
                LogUtil.i("广告规则-加载完成!");
            }
        });
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // return super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }


    @Override
    public void onCreate() {
        super.onCreate();

        LogUtil.i("广告狗后台服务=>启动");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        LogUtil.i("广告狗后台服务=>销毁");
        mInstance = null;
        executor.shutdown(); // 关闭执行的任务
    }

    private int notificationId = 10;

    public void showNotification() {
        Context context = this;
        // 创建通知渠道
        CharSequence name = "广告监听服务已启动";
        String description = "如需设置监听类型，点此进入设置";

        NotificationManager notificationManager = null;

        // 创建通知渠道
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("channel_id", "Channel Name", NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription("Channel Description");

            // 创建通知管理器
            notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }

        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        // 构建通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "lis")
                .setSmallIcon(R.drawable.link)
                .setContentTitle(name)
                .setContentText(description)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        // 发起通知
        notificationManager.notify(notificationId, builder.build());
    }

}
